package com.lp.model.utils;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * 密码加盐加密
 */

public class PasswordUtils {

    /**
     * 加密
     * @param password
     * @return
     */
    public static String encrypt(String password) {
        //1.生成 32 位随机盐值
        String salt = UUID.randomUUID().toString().replace("-", "");
        //2.盐值 + 密码 => md5 加密
        String md5SaltPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        //3.拼接盐值
        String finalPassword = salt + "$" + md5SaltPassword;
        return finalPassword;
    }

    /**
     * 解密：相同的方式加密
     * @param inputPassword
     * @param dbPassword
     * @return
     */
    private static String encrypt(String inputPassword, String dbPassword) {
        //1.拿到盐值
        String salt = dbPassword.split("\\$")[0];
        //2.盐值 + 密码 => md5 加密
        String md5SaltPassword = DigestUtils.md5DigestAsHex((salt + inputPassword).getBytes());
        //3.拼接盐值
        String finalPassword = salt + "$" + md5SaltPassword;
        return finalPassword;
    }

    public static boolean check(String inputPassword, String dbPassword) {
        //1.校验数据格式
        if(StringUtils.hasLength(inputPassword) && StringUtils.hasLength(dbPassword) &&
        dbPassword.length() == 65) {
            String confirmPassword = encrypt(inputPassword, dbPassword);
            return confirmPassword.equals(dbPassword);
        }
        return false;
    }

}
